/****************************************************************************
 *
 * Project: LPC-2478-STK
 *
 * Copyright: Ivan Vasilev, Olimex Ltd. All rights reserved.
 *
 * File: adc.h
 * Description: ADC functionality
 * Developer: Ivan Vasilev, <ivan at l123.org>
 *
 * Last change: $Date: 2009/07/15 21:17:16 $
 * Revision: $Revision: 1.1 $
 * Id: $Id: adc.c,v 1.1 2009/07/15 21:17:16 felipe Exp $
 * Author: $Author: felipe $
 *
 ****************************************************************************/

#include "adc.h"

void 	InitADC(UNS_8 channel)
{
	UNS_8 div;
	
	if (channel > 7) channel = 0;
	
	PCONP |= 1<<12;
	
	switch (channel)
	{
		case ADC_CH_0:
			PINSEL1 &= ~(0x03<<14);
			PINSEL1 |= 0x01 << 14;
			break;
		
		case ADC_CH_1:
			PINSEL1 &= ~(0x03<<16);
			PINSEL1 |= 0x01 << 16;
			break;
			
		case ADC_CH_2:
			PINSEL1 &= ~(0x03<<18);
			PINSEL1 |= 0x01 << 18;
			break;
			
		case ADC_CH_3:
			PINSEL1 &= ~(0x03<<20);
			PINSEL1 |= 0x01 << 20;
			break;
			
		case ADC_CH_4:
			PINSEL3 |= 0x03 << 28;
			break;
			
		case ADC_CH_5:
			PINSEL3 |= 0x03 << 30;
			break;
			
		case ADC_CH_6:
			PINSEL0 |= 0x03 << 24;
			break;
			
		case ADC_CH_7:
			PINSEL0 |= 0x03 << 26;
			break;
	}
	
	
	div = ( CPU_CLOCK_HZ / ADC_CLOCK_RATE) + 1;
	
	AD0CR  = 0x00000000;
	AD0CR |= div << 8;
	AD0CR |= 0x01 << 21;
	
}

UNS_32 GetADC(UNS_8 channel)
{
	UNS_32 result;
	
	if (channel > 7) channel = 0;
	AD0CR |= 0x01 << channel; 	/* select the channel */
	AD0CR |= 0x01 << 24;
	
	while (!(AD0GDR>>31));		/* wait for completion */
	
	AD0CR &= ~(0x07 << 24);
	
	if ((AD0GDR>>30)&0x1 == 1) return 0;
	
	result = (AD0GDR>>6)&0x3FF;
	
	return result;	
}
